package dian.qing.li.demo.security.config.security;

import com.alibaba.fastjson.JSON;
import com.pactera.redis.utils.RedisUtils;
import dian.qing.li.demo.security.commons.RestResult;
import dian.qing.li.demo.security.constants.Constants;
import dian.qing.li.demo.security.constants.RedisKey;
import dian.qing.li.demo.security.utils.JwtUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证成功
 *
 * @author: liqingdian
 **/
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails details = (UserDetails) authentication.getPrincipal();
        // 登陆成功后清除锁
        String lockedKey = RedisUtils.redisKey(RedisKey.LOGIN_LOCKED, details.getUsername());
        RedisUtils.delete(lockedKey);
        // 生成TOKEN，并缓存TOKEN
        String token = JwtUtils.token(details);
        Map<String, Object> data = new HashMap<>();
        data.put("username", details.getUsername());
        data.put("token", token);
        response.setHeader("Authorization", token);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_OK);
        RestResult succeed = RestResult.succeed("登陆成功", data);
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(succeed, Constants.FASTJSON_SERIALIZER));
        out.flush();
        out.close();
    }
}
